import Vue from 'vue'
import Router from 'vue-router'
// 登录页面
const Login = () => import(/* webpackChunkName: "login" */ '../components/Login.vue')
// 首页和欢迎页面
const Home = () => import(/* webpackChunkName: "home" */ '../components/Home.vue')
const Welcome = () => import(/* webpackChunkName: "home" */ '../components/Welcome.vue')
// 用户管理
const Users = () => import(/* webpackChunkName: "users" */ '../components/user/Users.vue')
// 权限管理
const Rights = () => import(/* webpackChunkName: "rights" */ '../components/power/Rights.vue')
const Roles = () => import(/* webpackChunkName: "rights" */ '../components/power/Roles.vue')
// 商品管理
const Categories = () => import(/* webpackChunkName: "goods" */ '../components/goods/Categories.vue')
const Params = () => import(/* webpackChunkName: "goods" */ '../components/goods/Params.vue')
const Goods = () => import(/* webpackChunkName: "goods" */ '../components/goods/Goods.vue')
const AddGoods = () => import(/* webpackChunkName: "goods" */ '../components/goods/AddGoods.vue')
// 订单管理
const Orders = () => import(/* webpackChunkName: "orders" */ '../components/Orders.vue')
// 数据管理
const Reports = () => import(/* webpackChunkName: "reports" */ '../components/Reports.vue')

Vue.use(Router)

const router =  new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    { 
      path: '/home', 
      component: Home,
      redirect: '/welcome',
      children: [
        {
          path: '/welcome',
          component: Welcome
        },
        {
          path: '/users',
          component: Users
        },
        {
          path: '/rights',
          component: Rights
        },
        {
          path: '/roles',
          component: Roles
        },
        {
          path: '/categories',
          component: Categories
        },
        {
          path: '/params',
          component: Params
        },
        {
          path: '/goods',
          component: Goods
        },
        {
          path: '/goods/add',
          component: AddGoods
        },
        {
          path: '/orders',
          component: Orders
        },
        {
          path: '/reports',
          component: Reports
        }
      ]
    }
  ]
})

// 路由全局守卫，在跳转之前
router.beforeEach((to, from, next)=>{
  // 只有调用next才可以放行，不然是进不去的，还可以指定跳转到其他的路由 next('/login')
  // 对所有的路由拦截进行判断是否登陆处理，
  
  // 如果用户登陆了，直接放行
  if(sessionStorage.getItem('token')){
    next()
  }else{
    // 如果用户没有登录
    // 但是用户访问的是登录页面：next()
    if(to.path === '/login'){
      next()
    }else{
      // 访问的不是登陆页面：next('/login')
      next('/login')
    }
  }
})

export default router
